package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.exception.BusinessException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.util.JwtUtil;
import com.atguigu.lease.common.util.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.util.HttpUtils;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author liangtianzhe
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public String getCode(String phone) {
        if(StringUtils.isBlank(phone)){
            throw new BusinessException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        String verifyCode = VerifyCodeUtil.getVerifyCode(6);
        this.sendMessage(phone,verifyCode);
        stringRedisTemplate.opsForValue().set(phone,verifyCode,2, TimeUnit.MINUTES);
        return "";
    }

    private void sendMessage(String phone, String verifyCode) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "fffd8a97551b45f3a95817c9a8aa5850";
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", phone);
        querys.put("param", "**code**:"+verifyCode+",**minute**:2");
        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        if(StringUtils.isBlank(phone)){
            throw new BusinessException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        String code = loginVo.getCode();
        if(StringUtils.isBlank(code)){
            throw new BusinessException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        if(!stringRedisTemplate.hasKey(phone)){
            throw new BusinessException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if(!Objects.equals(code,stringRedisTemplate.opsForValue().get(phone))){
            throw new BusinessException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //判断用户是否存在，不存在，代表首次登录，添加用户信息
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = userInfoMapper.selectOne(userInfoLambdaQueryWrapper);
        if(userInfo == null){
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-"+phone.substring(5));
            userInfoMapper.insert(userInfo);
        }
        if(Objects.equals(userInfo.getStatus(),BaseStatus.DISABLE)){
            throw new BusinessException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //生成Token
        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
    }
}
